package com.dtkavin.threads.mutual;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by john on 10/4/16.
 * 信号量，同样是互斥
 * 别的互斥是同一时间只有一个可以跑，这个可以有多个可以跑。
 * 信号量的锁，可以由其它线程来释放这个锁，普通的互斥做不到，这个可以用于死锁恢复的场合
 */
public class SemaphoneDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        final ShareData shareData = new ShareData();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    shareData.run();
                }
            }).start();

        }
        executorService.shutdown();

    }

    static class ShareData {
        Semaphore semaphore = new Semaphore(3);

        public void run() {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("run : " + Thread.currentThread().getName());
            System.out.println("semaphore available : " + semaphore.availablePermits());
            semaphore.release();
        }
    }
}
